package practicejava.threads;

public class EvenOddPrinter
{
    private static boolean myShouldPrintEven = true;

    /**
     * Runnable to be instantiated one for the even printing and one for the 
     * odd printing.
     */
    public static class NumPrinter implements Runnable
    {
        private boolean myIsEven;
        private int myNum;
        private Object myMonitor;

        public NumPrinter(boolean isEven, Object monitor)
        {
            myIsEven = isEven;
            myMonitor = monitor;

            if (myIsEven) {
                myNum = 0;
            }
            else {
                myNum = 1;
            }

        }

        @Override
        public void run()
        {
            while (myNum < 30) {
                synchronized (myMonitor) {
                    while((myIsEven && !myShouldPrintEven) || 
                            (!myIsEven && myShouldPrintEven)) 
                    {
                        try {
                            myMonitor.wait();
                        }
                        catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }    
                    }
                    System.out.println("Num: " + myNum);
                    myNum +=2;
                    myShouldPrintEven = !myShouldPrintEven;
                    myMonitor.notify();
                }
            }
        }
    }

    public static void main(String[] args)
    {
        Object monitor = new Object();
        Thread evenTh = new Thread(new NumPrinter(true, monitor));
        Thread oddTh = new Thread(new NumPrinter(false, monitor));
        evenTh.start();
        oddTh.start();
    }
}
